import type {Directive} from 'vue'

/**
 * 1.拖拽指令，父元素必须设置position:relative
 * 2.拖拽元素设置绝对定位，根据鼠标移动的位置设置left与top
 */

interface Eltype extends HTMLElement {
    parentNode:any
}

const draggable:Directive = {
    mounted:function(el:Eltype){
        el.style.cursor = 'move'
        el.style.position = 'absolute'
        el.onmousedown = function(e){
            let divX = e.pageX - el.offsetLeft
            let divY = e.pageY - el.offsetTop
            // 为什么用document：如果绑定到元素本身的情况下，鼠标拖动过快，鼠标会离开拖拽的元素，导致拖拽一段距离，拖拽失效的问题
            document.onmousemove = function(e){
                let left = e.pageX - divX
                let top = e.pageY - divY
                let maxTop = el.parentNode.offsetHeight - el.offsetHeight
                let maxLetf = el.parentNode.offsetWidth - el.offsetWidth
                if(left < 0){
                    left = 0
                }
                if(left>maxLetf){
                    left = maxLetf
                }
                if(top < 0){
                    top = 0
                }
                if(top > maxTop){
                    top = maxTop
                }

                el.style.left = left + 'px'
                el.style.top = top + 'px'
            }
            document.onmouseup = function(e){
                document.onmousemove = document.onmouseup = null
            }
        }
    }
}

export default draggable
